#!/usr/bin/env python
import traceback
import platform
import cProfile
from player_submission import OpenMoveEvalFn, CustomEvalFn, CustomPlayer
from isolation import Board, game_as_text
from test_players import RandomPlayer, HumanPlayer
from custom_min_max_player import CustomPlayerMinMax
from timeit import  repeat

if platform.system() != 'Windows':
   import resource
from time import time, sleep

win_times = 0
total_games = 10
time_cost = []
def single_run():
    global win_times
    try:
        #r = CustomPlayerMinMax()
        p1 = CustomPlayerMinMax(search_depth = 4)
        p2 = CustomPlayerMinMax(search_depth = 2)
        #h = RandomPlayer()
        # r = CustomPlayer( search_depth = 4)
        # h = CustomPlayerMinMax( search_depth = 2)
        #h = CustomPlayer()
        game = Board(p1, p2, 7, 7)
        output_b = game.copy()
        winner, move_history, termination = game.play_isolation(time_limit=100000, print_moves=False)
        print "\n",winner," has won. Reason: ", termination
        if winner == game.__queen_1__:
            win_times+=1

        # Uncomment to see game
        # print game_as_text(winner, move_history, termination, output_b)
    except NotImplementedError:
        print 'CustomPlayer Test: Not Implemented'
    except:
        print 'CustomPlayer Test: ERROR OCCURRED'
        print traceback.format_exc()


def do_test():
    global time_cost
    time_cost = repeat("single_run()", "from __main__ import single_run", number=1, repeat=total_games)


def main():

    """Example test you can run
    to make sure your AI does better
    than random."""
    print ""
    cProfile.run("do_test()")
    print "\nFirst player win rate:", win_times*1.0/total_games
    print "\neverage time cost:", sum(time_cost)/total_games, "s"

if __name__ == "__main__":
    main()
